package com.jinmdz.fmis.api.rec.service;

import com.jinmdz.fmis.api.api.model.common.IdData;
import com.jinmdz.fmis.api.api.model.common.IdVersionData;
import com.jinmdz.fmis.api.base.BaseService;
import com.jinmdz.fmis.api.model.system.UserItem;
import com.jinmdz.fmis.api.rec.model.recdispatchcar.RecDispatchCarData;
import com.jinmdz.fmis.common.util.BeanUtil;
import com.jinmdz.fmis.common.util.DataUtil;
import com.jinmdz.fmis.core.base.BaseResult;
import com.jinmdz.fmis.core.exception.ActionException;
import com.jinmdz.fmis.core.model.SearchLoadData;
import com.jinmdz.fmis.dao.dao.RecInfoDao;
import com.jinmdz.fmis.dao.model.dispatchcar.DispatchCar;
import com.jinmdz.fmis.dao.model.recinfo.RecInfoDispatchSearch;
import com.jinmdz.fmis.dao.model.recinfo.RecInfoWx;
import com.jinmdz.fmis.mapper.entity.RecDispatchCarEntity;
import com.jinmdz.fmis.mapper.entity.RecDriverEntity;
import com.jinmdz.fmis.mapper.entity.RecPorterEntity;
import com.jinmdz.fmis.mapper.mapper.RecDispatchCarMapper;
import com.jinmdz.fmis.mapper.mapper.RecDriverMapper;
import com.jinmdz.fmis.mapper.mapper.RecInfoMapper;
import com.jinmdz.fmis.mapper.mapper.RecPorterMapper;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.ArrayList;

/**
 * @author zhanglr
 * @date 2020/6/11 14:23
 */
@Service
public class DispatchCarService extends BaseService {

    @Resource
    private RecInfoMapper recInfoMapper;
    @Resource
    private RecDispatchCarMapper recDispatchCarMapper;
    @Resource
    private RecInfoDao recInfoDao;
    @Resource
    private RecDriverMapper recDriverMapper;
    @Resource
    private RecPorterMapper recPorterMapper;

    /**
     * 加载车辆调度信息列表dispatch_car表中
     *
     * @param
     * @return
     * @author ZhangLiRui
     * @date 2020-6-11 14:56
     */
    public BaseResult loadDispatchCarAll(UserItem userItem, RecInfoDispatchSearch data) {
        // 初始化分页数据
        startPageData(data);
        ArrayList<RecInfoWx> listRecInfoEntity = recInfoDao.listRecInfoSearch(data);
        //查询分页，只查询一次
        SearchLoadData<RecInfoWx> responseData = getSearchLoadData(listRecInfoEntity);

        return successData(responseData);
    }

    /**
     * 保存车辆调度信息
     *
     * @param userItem
     * @param data
     * @return
     * @author GaoXiangLiang
     * @date 2020-06-19 14:41
     */
    @Transactional(rollbackFor = Exception.class)
    public BaseResult saveDispatchCar(UserItem userItem, RecDispatchCarData data) throws ActionException {
        //主键id
        Integer id = data.getId();
        if (null != data && data.getId() != null) {
            //查询接运信息的调度信息是否存在，如已存在，取已存在调度数据

            DispatchCar dispatchCar = recInfoDao.getDispatchCarByRecId(data.getRecId());
            if (DataUtil.isNull(dispatchCar) && data.getId().toString().equals("0")) {
                RecDispatchCarEntity recDispatchCarEntity = getEntity(userItem, RecDispatchCarEntity.class);
                String funeralParlourCode = recDispatchCarEntity.getFuneralParlourCode();
                BeanUtil.copy2Bean(data, recDispatchCarEntity);
                recDispatchCarEntity.setFuneralParlourCode(funeralParlourCode);
                id = insertDispatchCar(userItem, data);
            } else {
                id = this.updateDispatchCar(userItem, data);
            }
        } else {
            return failure("数据不能为空");
        }
        //返回调度车辆信息
        return this.loadDispatchCarWithId(new IdData().setId(id));
    }

    /**
     * 保存调度车辆信息
     *
     * @param userItem
     * @param data
     * @return
     * @author GaoXiangLiang
     * @date 2020-06-19 14:41
     */
    @Transactional(rollbackFor = Exception.class)
    public Integer insertDispatchCar(UserItem userItem, RecDispatchCarData data) throws ActionException {
        RecDispatchCarEntity entity = getEntity(userItem, RecDispatchCarEntity.class);
        String funeralParlourCode = entity.getFuneralParlourCode();
        // 覆盖数据
        BeanUtil.copy2Bean(data, entity);
        //将生成的殡仪馆代码
        entity.setFuneralParlourCode(funeralParlourCode);
        recDispatchCarMapper.insertRecDispatchCar(entity);
        //保存抬尸工与司机id的数组
        //保存接运司机信息
        ArrayList<Integer> recInfoDriver = data.getRecInfoDriver();
        if (recInfoDriver != null && recInfoDriver.size() > 0) {
            for (Integer id : recInfoDriver) {
                RecDriverEntity recDriverEntity = getEntity(userItem, RecDriverEntity.class)
                        .setRecId(data.getRecId())
                        .setSystemUserId(id);

                //插入接运司机数据
                recDriverMapper.insertRecDriver(recDriverEntity);

                if (DataUtil.invalid(entity.getId())) {
                    throw exception("保存抬尸工信息失败");
                }

            }

        }

        //保存抬尸工信息
        ArrayList<Integer> recInfoPorter = data.getRecInfoPorter();

        if (recInfoPorter != null && recInfoPorter.size() > 0) {
            for (Integer id : recInfoPorter) {
                RecPorterEntity recPorterEntity = getEntity(userItem, RecPorterEntity.class)
                        .setRecId(data.getRecId())
                        .setSystemUserId(id);
                //保存抬尸工数据
                recPorterMapper.insertRecPorter(recPorterEntity);

                if (DataUtil.invalid(entity.getId())) {
                    throw exception("保存接运司机信息失败");
                }

            }

        }
        // 判断保存信息结果
        if (DataUtil.invalid(entity.getId())) {
            throw exception("保存信息失败");
        }
        return entity.getId();
    }

    /**
     * 保存调度车辆信息
     *
     * @param userItem
     * @param data
     * @return
     * @author GaoXiangLiang
     * @date 2020-06-19 14:41
     */
    @Transactional(rollbackFor = Exception.class)
    public Integer updateDispatchCar(UserItem userItem, RecDispatchCarData data) throws ActionException {
        // 验证主键和数据版本是否存在
        if (DataUtil.isNull(data.getId(), data.getVersion())) {
            throw exception("请求主键与版本号不能为空");
        }

        RecDispatchCarEntity entity = recDispatchCarMapper.getRecDispatchCarById(data.getId());
        if (DataUtil.isNull(entity) || DataUtil.isNull(entity.getId(), entity.getVersion())) {
            throw exception("类型主键错误，不存在此类型信息");
        }

        // 验证信息版本
        if (!DataUtil.equals(data.getVersion(), entity.getVersion())) {
            throw exception(versionError("车辆调度版本信息"));
        }

        //修改数据
        recDispatchCarMapper.updateRecDispatchCar(entity);
        //更新抬尸工
        updateRecTaskPorter(userItem, data, data.getRecId());
        //更新司机
        updateRecInfoDriver(userItem, data, data.getRecId());
        return entity.getId();
    }

    /**
     * @param
     * @return
     * @author GaoXiangLiang
     * @date 2020-6-19 11:42
     */
    @Transactional(rollbackFor = Exception.class)
    public BaseResult deleteRecDispatchCarwithId(UserItem userItem, IdVersionData data) throws ActionException {
        // 判断删除主键集合是否存在
        if (data == null || DataUtil.invalid(data.getId())) {
            throw exception("不存在要删除信息的主键");
        }

        if (DataUtil.isNull(data.getVersion())) {
            throw exception("版本号不能为空");
        }

        RecDispatchCarEntity entity = recDispatchCarMapper.getRecDispatchCarById(data.getId());

        if (entity == null || DataUtil.invalid(entity.getId())) {
            throw exception("主键错误,不存在此信息");
        }

        if (!DataUtil.equals(data.getVersion(), entity.getVersion())) {
            throw exception(versionError("车辆调度信息"));
        }

        recDispatchCarMapper.deletedForRecDispatchCar(data.getId(), userItem.getId(), data.getVersion());

        return success("删除完成");
    }

    /**
     * 根据rec_info表中id加载接运打印二维码数据
     *
     * @param data
     * @return
     * @author GaoXiangLiang
     * @date 2020-06-16 10:44
     */

    public BaseResult loadDispatchCarWithId(IdData data) {
        if (DataUtil.isNull(data) == null || DataUtil.invalid(data.getId())) {
            return failure("业务主键为空");
        }
        //响应实体
        RecDispatchCarData resultData = new RecDispatchCarData();
        //根据rec_info表中id加载接运信息
        RecDispatchCarEntity recDispatchCarEntity = recDispatchCarMapper.getRecDispatchCarById(data.getId());
        if (DataUtil.isNull(recDispatchCarEntity)) {
            return failure("业务主键不存在");
        }
        //接运信息响应实体
        BeanUtil.copy2Bean(recDispatchCarEntity, resultData);
        //接运司机
        ArrayList<Integer> recInfoDriver = recInfoDao.listRecDriverByRecId(data.getId());
        resultData.setRecInfoDriver(recInfoDriver);
        //抬尸工
        ArrayList<Integer> recInfoPorter = recInfoDao.listRecPorterByRecId(data.getId());
        resultData.setRecInfoPorter(recInfoPorter);
        return successData(resultData);
    }

    /**
     * 更新接运信息抬尸工信息
     *
     * @param userItem 当前帐号
     * @param data     接运数据
     * @param recId    接运任务
     * @return
     * @author GaoXiangLiang
     * @date 2020-06-17 11:05
     */
    private void updateRecTaskPorter(UserItem userItem, RecDispatchCarData data, Integer recId) throws
            ActionException {

        // 处理抬尸工
        if (DataUtil.invalid(data.getRecInfoPorter())) {
            // 清除抬尸工
            recInfoDao.deletedRecTaskPorter(recId, userItem.getId());
        } else {
            // 去重
            data.setRecInfoPorter(DataUtil.repeatArrayList(data.getRecInfoPorter()));

            // 处理抬尸工
            ArrayList<Integer> userIds = recInfoDao.listRecPorterByRecId(data.getId());
            for (Integer userId : data.getRecInfoPorter()) {
                if (DataUtil.invalid(userId)) {
                    continue;
                }
                if (userIds.contains(userId)) {
                    userIds.remove(userId);
                } else {
                    RecPorterEntity porterEntity = getEntity(userItem, RecPorterEntity.class);
                    porterEntity.setRecId(recId)
                            .setSystemUserId(userId);
                    recPorterMapper.insertRecPorter(porterEntity);
                    if (DataUtil.isNull(porterEntity.getId())) {
                        throw exception("保存接运任务抬尸工信息失败");
                    }
                }
            }

            // 去除多余的抬尸工
            if (userIds.size() > 0) {
                // 清除抬尸工
                recInfoDao.deletedRecInfoPorterByUserIds(recId, userItem.getId(), userIds);
            }
        }
    }

    /**
     * 更新接运信息司机信息
     *
     * @param userItem 当前帐号
     * @param data     接运数据
     * @param recId    接运任务
     * @return
     * @author GaoXiangLiang
     * @date 2020-06-17 11:05
     */
    private void updateRecInfoDriver(UserItem userItem, RecDispatchCarData data, Integer recId) throws
            ActionException {

        // 处理抬尸工
        if (DataUtil.invalid(data.getRecInfoPorter())) {
            // 清除抬尸工
            recInfoDao.deletedRecDriver(recId, userItem.getId());
        } else {
            // 去重
            data.setRecInfoDriver(DataUtil.repeatArrayList(data.getRecInfoDriver()));

            // 获得司机
            ArrayList<Integer> userIds = recInfoDao.listRecDriverByRecId(data.getId());
            for (Integer userId : data.getRecInfoDriver()) {
                if (DataUtil.invalid(userId)) {
                    continue;
                }
                if (userIds.contains(userId)) {
                    userIds.remove(userId);
                } else {
                    RecDriverEntity recDriverEntity = getEntity(userItem, RecDriverEntity.class);
                    recDriverEntity.setRecId(recId)
                            .setSystemUserId(userId);
                    recDriverMapper.insertRecDriver(recDriverEntity);
                    if (DataUtil.isNull(recDriverEntity.getId())) {
                        throw exception("保存接运信息司机失败");
                    }
                }
            }

            // 去除多余的司机
            if (userIds.size() > 0) {
                // 清除司机
                recInfoDao.deletedRecInfoDriverByUserIds(recId, userItem.getId(), userIds);
            }
        }
    }
}
